/* @flow */

import {
  isDef, 
  isUndef,
  extend
} from '../../../../util/index'

const importantRE = /\s*!important$/
const setProp = (el, name, val) => {
  if (importantRE.test(val)) {
    el.style.setProperty(name, val.replace(importantRE, ''), 'important')
  } else {
    el.style[name] = val
  }
}

function updateStyle (oldVnode, vnode) {
  const data = vnode.data
  const oldData = oldVnode.data

  if (isUndef(data.staticStyle) && isUndef(data.style) &&
    isUndef(oldData.staticStyle) && isUndef(oldData.style)
  ) {
    return
  }

  let cur, name
  const el = vnode.elm
  const oldStaticStyle = oldData.staticStyle
  const oldStyleBinding = oldData.normalizedStyle || oldData.style || {}

  const oldStyle = oldStaticStyle || oldStyleBinding

  let style = vnode.data.style
  if(Array.isArray(vnode.data.style)){
    const res = {}
    for (let i = 0; i < vnode.data.style.length; i++) {
      if (vnode.data.style[i]) {
        extend(res, vnode.data.style[i])
      }
    }
    style = res
  }
  
  //拷贝一份不是被观测的ob值
  vnode.data.normalizedStyle = isDef(style.__ob__)
    ? extend({}, style)
    : style

  const newStyle =  vnode.data.normalizedStyle

  for (name in oldStyle) {
    if (isUndef(newStyle[name])) {
      setProp(el, name, '')
    }
  }
  for (name in newStyle) {
    cur = newStyle[name]
    if (cur !== oldStyle[name]) {
      setProp(el, name, cur == null ? '' : cur)
    }
  }
  if(Object.keys(newStyle).length === 0 && vnode.staticStyle){
      el.setAttribute('style', vnode.staticStyle) 
  }
}

export default {
  create: updateStyle,
  update: updateStyle
}
